package com.archermind.style.interceptor;

import com.archermind.style.bean.User;
import com.archermind.style.util.SessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = SessionUtil.getCurUser();
        if(user != null) {
            if(user.getId()==1){
                return true;
            }else{
                HandlerMethod method = (HandlerMethod)handler;
                Auth auth = method.getMethodAnnotation(Auth.class);
                if(auth == null){
                    auth =  method.getBeanType().getAnnotation(Auth.class);
                }
                if(auth == null){
                    return true;
                }else{
                    String authStr = auth.value();
                    if(StringUtils.isNotEmpty(user.getPower()) && user.getPower().indexOf(authStr)>-1){
                        return true;
                    }
                }
            }
        }
        String uri = request.getRequestURI();
        if (uri.startsWith("/admin/main.html")) {
            response.sendRedirect("login.html");
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            PrintWriter writer = response.getWriter();
            writer.write("{\"code\":\""+HttpStatus.UNAUTHORIZED.value()+"\"}");
            writer.flush();
            writer.close();
        }
        return false;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {

    }
}
